<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品管理</title>
    <!-- 引入 Vue 和 Element UI 的样式文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui/lib/theme-chalk/index.css">
    <!-- 引入 Vue、Element UI 和 Axios 的 JavaScript 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.1/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .el-table {
            border: 1px solid #e0e0e0; /* 添加表格边框 */
        }
        .el-table tr.el-table__row:nth-child(odd) {
            background-color: #f7f7f7; /* 斑马线效果 */
        }
        .table-image {
            max-width: 100px;
            max-height: 100px;
        }
    </style>
</head>
<body>
<div id="app">
    <el-container>
        <!-- 右侧内容区域 -->
        <el-main>
            <h2>商品列表</h2>
            <el-button type="primary" @click="showAddDialog">添加商品</el-button>
            <br>
            <br>
            <el-table :data="products" style="width: 100%" border>
                <el-table-column prop="productId" label="ID" width="80"></el-table-column>
                <el-table-column prop="productName" label="商品名称"></el-table-column>
                <el-table-column prop="description" label="描述"></el-table-column>
                <el-table-column prop="imageUrl" label="图片">
                    <template slot-scope="scope">
                        <el-image
                                v-if="scope.row.imageUrl"
                                :src="scope.row.imageUrl"
                                :preview-src-list="[scope.row.imageUrl]"
                                alt="商品图片"
                                class="table-image">
                        </el-image>
                        <span v-else>暂无图片</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button type="text" @click="showEditDialog(scope.row)">编辑</el-button>
                        <el-button type="text" @click="handleDelete(scope.row.productId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>

        <!-- 添加和编辑商品的模态框 -->
        <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose"
        >
            <el-form :model="currentProduct" ref="productForm" label-width="80px">
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="currentProduct.productName"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="currentProduct.description"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <el-upload
                            action="/upload"
                            :show-file-list="false"
                            :on-success="handleUploadSuccess"
                            :before-upload="beforeUpload"
                            accept="image/*"
                    >
                        <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                    </el-upload>
                    <br>
                    <img v-if="imageUrl" :src="imageUrl" alt="上传的图片预览" class="table-image">
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveProduct">确 定</el-button>
            </div>
        </el-dialog>
    </el-container>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            products: [], // 商品列表数据
            dialogVisible: false, // 控制模态框显示隐藏
            dialogTitle: '', // 模态框标题
            currentProduct: { // 当前编辑的商品数据
                productId: '',
                productName: '',
                description: '',
                imageUrl: ''
            },
            imageUrl: '' // 用于预览上传的图片
        },
        created() {
            // 页面加载时获取所有商品列表
            this.getAllProducts();
        },
        methods: {
            // 获取所有商品列表
            getAllProducts() {
                axios.get('/product?operation=getAllProducts')
                    .then(response => {
                        this.products = response.data.data; // 假设返回的数据格式中有一个 data 字段存储商品列表
                    })
                    .catch(error => {
                        console.error('Error fetching products', error);
                    });
            },
            // 显示添加商品的模态框
            showAddDialog() {
                this.dialogTitle = '添加商品';
                this.currentProduct = {
                    productName: '',
                    description: '',
                    imageUrl: ''
                };
                this.imageUrl = ''; // 清空预览的图片
                this.dialogVisible = true;
            },
            // 显示编辑商品的模态框
            showEditDialog(product) {
                this.dialogTitle = '编辑商品';
                this.currentProduct = Object.assign({}, product); // 使用对象的深拷贝以避免直接修改原始数据
                this.imageUrl = product.imageUrl || ''; // 设置预览的图片
                this.dialogVisible = true;
            },
            // 处理模态框关闭
            handleClose(done) {
                this.$refs.productForm.resetFields(); // 重置表单
                this.currentProduct = { // 清空当前编辑的商品数据
                    productId: '',
                    productName: '',
                    description: '',
                    imageUrl: ''
                };
                this.imageUrl = ''; // 清空预览的图片
                done(); // 关闭模态框
            },
            // 处理上传前的校验
            beforeUpload(file) {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    this.$message.error('只能上传 JPG/PNG 格式的图片');
                }
                return isJpgOrPng;
            },
            // 处理上传成功
            handleUploadSuccess(response, file) {
                this.imageUrl = response; // 设置上传成功后的图片地址
            },
            // 保存商品
            saveProduct() {
                const params = {
                    productId: this.currentProduct.productId,
                    productName: this.currentProduct.productName,
                    description: this.currentProduct.description,
                    imageUrl: this.imageUrl
                };

                const operation = this.currentProduct.productId ? 'updateProduct' : 'addProduct';
                axios.post(`/product?operation=${operation}`, null, {
                    params: params
                })
                    .then(response => {
                        this.getAllProducts(); // 保存成功后刷新列表
                        this.dialogVisible = false; // 关闭模态框
                        this.$message.success(operation === 'addProduct' ? '添加商品成功' : '更新商品信息成功');
                    })
                    .catch(error => {
                        console.error('Error saving product', error);
                        this.$message.error(operation === 'addProduct' ? '添加商品失败' : '更新商品信息失败');
                    });
            },
            // 删除商品
            handleDelete(productId) {
                if (confirm('确定要删除该商品吗？')) {
                    axios.post('/product?operation=deleteProduct', null, {
                        params: { productId: productId }
                    })
                        .then(response => {
                            this.getAllProducts(); // 删除成功后刷新列表
                            this.$message.success('删除商品成功');
                        })
                        .catch(error => {
                            console.error('Error deleting product', error);
                            this.$message.error('删除商品失败');
                        });
                }
            }
        }
    });
</script>
</body>
</html>
